package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author zhengjd
 * @date 2020/5/11 23:51
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Controller
@RequestMapping("/search")
@CrossOrigin
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    /**
     * 搜索
     * @param searchMap
     * @return
     */
    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map searchMap, Model model){
        //调用search微服务的feign
        Map resultMap = skuFeign.search(searchMap);
        //将查询结果存入到model中
        model.addAttribute("result",resultMap);
        //将查询条件存到model中，用于回显到前端搜索框中
        model.addAttribute("searchMap",searchMap);
        //将url存到model中
        String url = getUrl(searchMap);
        model.addAttribute("url",url);

        //封装分页实体对象，存入到model中
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.valueOf(resultMap.get("total").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString()));
        model.addAttribute("page",page);
        return "search";
    }

    /**
     * 拼接url请求
     * @param searchMap
     * @return
     */
    private String getUrl(Map<String,String> searchMap) {
        //设置初始请求路径
        String url = "/search/list";
        if (searchMap != null && searchMap.size()>0){
            url+="?";  //拼接？添加请求参数
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                //如果有排序的参数，则直接跳过，由前端直接拼接
                if (key.equals("sortRule") || key.equals("sortField")){
                    continue;
                }
                //如果有分页的参数，也直接跳过，由前端直接拼接
                if (key.equals("pageNum") || key.equals("pageSize")){
                    continue;
                }
                url+=key+"="+value+"&";
            }
            //去除最后的“&”
            url = url.substring(0,url.length()-1);

        }

        return url;
    }
}
